package com.atguigu.srb.sms.listener;

import com.alibaba.fastjson.JSON;
import com.atguigu.srb.base.dto.SmsDTO;
import com.atguigu.srb.mq.consts.MqConsts;
import com.atguigu.srb.sms.service.SmsService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

@Component
@Slf4j
public class SmsMqListener {
    @Resource
    SmsService smsService;
    @RabbitListener(queues = {MqConsts.QUEUE_SMS_ITEM})
    public void sendMessage(SmsDTO smsDTO, Message message, Channel channel) throws IOException {
        try {
            log.info("短信发送成功:{}", JSON.toJSONString(smsDTO));
            //消费消息：执行业务
            smsService.sendMsg(smsDTO.getMobile(),smsDTO.getType());

            channel.basicAck(message.getMessageProperties().getDeliveryTag() , false);
        } catch (Exception e) {
            log.error(ExceptionUtils.getMessage(e));
            //出现异常时，先重试消费一次 再次消费异常丢弃消息(到达死信队列)
            if(message.getMessageProperties().isRedelivered()){
                channel.basicReject(message.getMessageProperties().getDeliveryTag() , false);
            }else{
                channel.basicNack(message.getMessageProperties().getDeliveryTag() ,false,true);
            }
        }
    }

}
